<template>
  <div class="list">

    <van-popup v-model="showForm" position="top" :style="{ height: '15%' }">

      <div style="position:fixed;z-index:1;width:100%; top:50px;left:0;">
        <!--      <div class="van-search" style="position:fixed;z-index:1;width:15vw;left:0vw;top:1vh;font-size:14px;line-height:34px;background:rgb(255,255,255);"><van-icon @click="returnHome" name="home-o" size="25px" /></div>-->
        <form action="/">
          <van-search v-if="this.idobject == 'dailyreports' || this.idobject == 'weekreports' || this.idobject == 'monthreport1'" placeholder="请输入人员名称" v-model="sval" clearable show-action @search="onSearch" @clear="onCancel" style="position:fixed;top:0vh;left:0vw;width:85vw;z-index:1">
            <template #action>
              <div style="color: #ff4d4f" @click="onSearch">搜索</div>
            </template>
          </van-search>
          <van-search :placeholder="`请输入${searchPh}`" v-model="sval" clearable show-action @search="onSearch" @clear="onCancel" style="position:fixed;top:0vh;left:0vw;width:85vw;z-index:1">
            <template #action>
              <div style="color: #ff4d4f" @click="onSearch">搜索</div>
            </template>
          </van-search>
        </form>
      </div>
    </van-popup>
    <!--      <div class="van-search" style="position:fixed;z-index:1;width:15vw;left:87vw;top:0.5vh;font-size:14px;line-height:34px;background:rgb(255,255,255);">筛选 <van-icon @click="showSearchPopup" size="25px" name="filter-o" /></div>-->

    <van-popup v-model="showDatePicker" position="top" :style="{ height: '30%' }">
      <van-datetime-picker v-model="currentDate" type="date" title="选择年月日" :min-date="minDate" :max-date="maxDate" :formatter="formatter" @confirm="confirmDate" />
    </van-popup>

    <van-popup v-model="showOpenRef" round position="bottom">
      <van-picker show-toolbar :columns="depcolumns" @cancel="showOpenRef = false" @confirm="onConfirmRef" />
    </van-popup>

    <van-popup v-model="searchshow" position="right" style="width:90vw;height:100vh">
      <div style="padding-top:1vh;padding-left:1vw;padding-right:1vw;">
        <form action="">
          <!--<van-field clearable v-for="condition in conditiondata" :key="condition.viewcondition_id" v-model="condition.viewcondition_value" :label="condition.viewcondition_title"/>-->
          <template v-if="searchshow && conditiondata.length > 0">
            <van-tree-select height="55vh" :items="items" :main-active-index.sync="mainactive">
              mainactive: 0,
              <template #content>
                <van-radio-group v-model="conditiondata[mainactive].viewcondition_uitype" v-if="conditiondata[mainactive].viewcondition_uitype === 'int' || conditiondata[mainactive].viewcondition_uitype === 'double' || conditiondata[mainactive].viewcondition_uitype === 'money' || conditiondata[mainactive].viewcondition_uitype === 'percent'">
                  <van-cell-group>
                    <van-cell title="等于" clickable @click="conditiondata[mainactive].viewcondition_comparison = 'eq'">
                      <template #right-icon>
                        <van-radio name="eq" />
                      </template>
                    </van-cell>
                    <van-cell title="!=" clickable @click="conditiondata[mainactive].viewcondition_comparison = 'noteq'">
                      <template #right-icon>
                        <van-radio name="noteq" />
                      </template>
                    </van-cell>
                    <van-cell title="大于" clickable @click="conditiondata[mainactive].viewcondition_comparison = 'bt'">
                      <template #right-icon>
                        <van-radio name="bt" />
                      </template>
                    </van-cell>
                    <van-cell title="大于等于" clickable @click="conditiondata[mainactive].viewcondition_comparison = 'bteq'">
                      <template #right-icon>
                        <van-radio name="bteq" />
                      </template>
                    </van-cell>
                    <van-cell title="小于" clickable @click="conditiondata[mainactive].viewcondition_comparison = 'lt'">
                      <template #right-icon>
                        <van-radio name="lt" />
                      </template>
                    </van-cell>
                    <van-cell title="小于等于" clickable @click="conditiondata[mainactive].viewcondition_comparison = 'lteq'">
                      <template #right-icon>
                        <van-radio name="lteq" />
                      </template>
                    </van-cell>
                    <van-cell title="空" clickable @click="conditiondata[mainactive].viewcondition_comparison = 'empty'">
                      <template #right-icon>
                        <van-radio name="empty" />
                      </template>
                    </van-cell>
                    <van-cell title="非空" clickable @click="conditiondata[mainactive].viewcondition_comparison = 'notempty'">
                      <template #right-icon>
                        <van-radio name="notempty" />
                      </template>
                    </van-cell>
                  </van-cell-group>
                </van-radio-group>
                <van-radio-group v-model="conditiondata[mainactive].viewcondition_comparison" v-else-if="conditiondata[mainactive].viewcondition_uitype === 'bool'">
                  <van-cell-group>
                    <van-cell title="=" clickable @click="conditiondata[mainactive].viewcondition_comparison = 'eq'">
                      <template #right-icon>
                        <van-radio name="eq" />
                      </template>
                    </van-cell>
                    <van-cell title="!=" clickable @click="conditiondata[mainactive].viewcondition_comparison = 'noteq'">
                      <template #right-icon>
                        <van-radio name="noteq" />
                      </template>
                    </van-cell>
                    <van-cell title="空" clickable @click="conditiondata[mainactive].viewcondition_comparison = 'empty'">
                      <template #right-icon>
                        <van-radio name="empty" />
                      </template>
                    </van-cell>
                    <van-cell title="非空" clickable @click="conditiondata[mainactive].viewcondition_comparison = 'notempty'">
                      <template #right-icon>
                        <van-radio name="notempty" />
                      </template>
                    </van-cell>
                  </van-cell-group>
                </van-radio-group>
                <van-radio-group v-model="conditiondata[mainactive].viewcondition_comparison" v-else-if="conditiondata[mainactive].viewcondition_uitype === 'datetime'">
                  <van-cell-group>
                    <!--                        <van-cell    :value="date" v-model="conditiondata[mainactive].viewcondition_value" title="选择单个日期"  @click="calendarShow = true" />-->
                    <!--                        <van-calendar  v-model="calendarShow" :show-confirm="false" position="right"  @confirm="onCalendarConfirm"  />-->

                    <van-cell title="等于" clickable @click="setValueForDatetime('eq')">
                      <template #right-icon>
                        <van-radio name="eq" />
                      </template>
                    </van-cell>

                    <van-cell title="大于" clickable @click="setValueForDatetime('bt')">
                      <template #right-icon>
                        <van-radio name="bt" />

                      </template>
                    </van-cell>

                    <van-cell title="大于等于" clickable @click="setValueForDatetime('bteq')">
                      <template #right-icon>
                        <van-radio name="bteq" />

                      </template>
                    </van-cell>

                    <van-cell title="小于" clickable @click="setValueForDatetime('lt')">
                      <template #right-icon>
                        <van-radio name="lt" />
                      </template>
                    </van-cell>

                    <van-cell title="小于等于" clickable @click="setValueForDatetime('lteq')">
                      <template #right-icon>
                        <van-radio name="lteq" />
                      </template>
                    </van-cell>

                  </van-cell-group>
                </van-radio-group>
                <van-radio-group v-model="conditiondata[mainactive].viewcondition_comparison" v-else>
                  <van-cell-group>
                    <van-cell title="包含" clickable @click="conditiondata[mainactive].viewcondition_comparison = 'in'">
                      <template #right-icon>
                        <van-radio name="in" />
                      </template>
                    </van-cell>
                    <van-cell title="不包含" clickable @click="conditiondata[mainactive].viewcondition_comparison = 'notin'">
                      <template #right-icon>
                        <van-radio name="notin" />
                      </template>
                    </van-cell>
                    <van-cell title="等于" clickable @click="conditiondata[mainactive].viewcondition_comparison = 'eq'">
                      <template #right-icon>
                        <van-radio name="eq" />
                      </template>
                    </van-cell>
                    <van-cell v-if="(((idobject == 'dailyreports' || idobject == 'weekreports' || idobject == 'monthreport1') && items[mainactive]['text'] === '负责人') || (idobject == 'activity' && items[mainactive]['text'] === '拜访执行人') || (idobject == 'xhjh' && items[mainactive]['text'] === '负责人') || (idobject == 'xsjhn' && items[mainactive]['text'] === '业务员') || (idobject == 'cptd' && items[mainactive]['text'] === '负责人'))" title="等于参照" clickable @click="setValueForRef('inby')">
                      <template #right-icon>
                        <van-radio name="inby" />
                      </template>
                    </van-cell>
                    <van-cell title="不等于" clickable @click="conditiondata[mainactive].viewcondition_comparison = 'noteq'">
                      <template #right-icon>
                        <van-radio name="noteq" />
                      </template>
                    </van-cell>
                    <van-cell title="空" clickable @click="conditiondata[mainactive].viewcondition_comparison = 'empty'">
                      <template #right-icon>
                        <van-radio name="empty" />
                      </template>
                    </van-cell>
                    <van-cell title="非空" clickable @click="conditiondata[mainactive].viewcondition_comparison = 'notempty'">
                      <template #right-icon>
                        <van-radio name="notempty" />
                      </template>
                    </van-cell>
                  </van-cell-group>
                </van-radio-group>

                <van-field v-model="conditiondata[mainactive].viewcondition_value" placeholder="请输入" />

              </template>
            </van-tree-select>
          </template>
          <div style="background:rgb(244,244,244);height:1vh"></div>
          <div style="padding-top:1vh;padding-left:2vw;padding-bottom:1vh;font-size:14px;">
            <van-radio-group v-model="radiovalue" direction="horizontal">
              <van-radio name="asc" icon-size="14px">升序</van-radio>
              <van-radio name="desc" icon-size="14px">降序</van-radio>
            </van-radio-group>
          </div>
          <input type="button" style="margin:1vw;width:27vw" :class="orderby == condition.viewcondition_field ? 'van-button van-button--primary van-button--small' : 'van-button van-button--default van-button--small'" v-for="condition in conditiondata" :key="condition.index" @click="chooseOrder(condition.viewcondition_field)" :value="condition.viewcondition_title" />
          <div style="background:rgb(244,244,244);height:1vh"></div>
          <button type="button" style="margin:1vw;" v-for="tag in searchtags" @click="chooseTag(tag.id)" :key="tag.id" :class="tag.tagclass.replaceAll('tag-large', 'tag-list')">{{ tag.sname }}<van-icon v-if="!(!searchedtags[tag.id])" name="success" /></button>
          <div style="background:rgb(244,244,244);height:1vh"></div>
          <!-- 不能使用van-button -->
          <input type="button" style="margin:1vw;width:27vw" class="van-button van-button--info van-button--small" value="查询" @click="query" />
          <input type="button" style="margin:1vw;width:27vw" class="van-button van-button--default van-button--small" value="清空" @click="clearquery" />
          <input type="button" style="margin:1vw;width:27vw" class="van-button van-button--default van-button--small" value="关闭" @click="searchshow = false" />
        </form>
      </div>
    </van-popup>
    <van-dropdown-menu style="position: fixed;z-index:1;width:33vw;left:0vw;top:0vh;font-size:14px;">
      <van-dropdown-item v-model="value1" :options="option1" @click.native="query" />
    </van-dropdown-menu>
    <div class="van-dropdown-item" @click="showSearchPopup" style="position:fixed;line-height: 48px;text-align: center; z-index:1;width:33vw;left:33vw;top:0vh;font-size:16px !important; background:rgb(255,255,255);">筛选&nbsp;&nbsp;<van-icon size="20px" name="filter-o" /> </div>
    <div @click="showFormPopup" style="position:fixed;z-index:1;width:33vw;line-height: 48px;text-align:center; left:66vw;top:0vh;font-size:16px !important; background:rgb(255,255,255);">搜索&nbsp;&nbsp; <van-icon size="21px" name="search" /></div>
    <div style="margin-top:48px;height:10px;background-color:whitesmoke"></div>
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh" style="margin-bottom:8vh;">
      <van-list v-model="loading" :finished="finished" finished-text="已加载全部数据" @load="onLoad">
        <template v-if="this.idobject == 'dailyreports' || this.idobject == 'weekreports' || this.idobject == 'monthreport1'">
          <!--  自己画-->
          <template v-for="item in list">
            <a :key="item.id" style="display:block;padding:8px;font-size:14px; font-family: 'Avenir', Helvetica, Arial, sans-serif; background-color: #fff; margin-bottom: 5px; border-bottom: 1px solid #F5F6F7" v-on:click.stop="openCard(item[idobject + '_id'])">
              <div style="clear:both;position:relative;">
                <div style="float: left;width:50px;margin-top:14px;color:#000">
                  <div v-html="item.title"></div>
                </div>
                <div style="float:left;margin-left:5px;margin-top:5px;width:250px;">
                  <span style="margin-top:14px;display: block;line-height: 20px;color: #969799" v-html="item.label"></span>
                </div>
                <div style="position:absolute;top:14px;right:3px;">
                  <div style="" v-html="item.value"></div>
                </div>
              </div>
            </a>
            <!--          <van-cell :value="item.value" @click="openCard(item[idobject + '_id'])">-->
            <!--            <template #title>-->
            <!--              <span>{{ item.title }}</span><br>-->
            <!--              <span style="font-size: 12px;color: #969799;" v-html="item.label"></span>-->
            <!--            </template>-->
            <!--          </van-cell>-->
          </template>
          <div style="clear:both"></div>
        </template>
        <template v-else>
          <van-swipe-cell v-for="item in list" :key="item.id">
            <template slot="left">
              <template v-if="isflow === '1'">
                <van-button v-if="!item[idobject + '_billstatus'] || item[idobject + '_billstatus'] === '40282e81535903f901535938d3be0748' || item[idobject + 'billstatus'] === '2c9a2d9270d1ac600170d33c44b800a7'" class="swipe-button" square type="info" text="提交" @click="submit(item[idobject + '_id'])" />
                <van-button v-else class="swipefont-size: 12px; color: rgb(150, 151, 153)-button" square disabled type="info" text="提交" @click="submit(item[idobject + '_id'])" />
              </template>
              <van-button v-if="!item[idobject + '_billstatus'] || item[idobject + '_billstatus'] === '40282e81535903f901535938d3be0748' || item[idobject + 'billstatus'] === '2c9a2d9270d1ac600170d33c44b800a7'" class="swipe-button" square type="primary" text="编辑" @click="edit(item[idobject + '_id'])" />
              <van-button v-else class="swipe-button" square disabled type="primary" text="编辑" @click="edit(item[idobject + '_id'])" />
            </template>
            <van-cell @click="openCard(item[idobject + '_id'])">
              <template #title>
                <h4 style="margin:0px; font-size: 16px;" v-html="item.title"></h4>
                <!--                <span v-html="item.tags ? item.tags.replaceAll('tag-large', '') : ''"></span><br/>-->
                <div v-html="item.tags && item.tags.replaceAll('tag-large', '')"></div>
                <div style="font-size: 12px;color: #969799;" v-html="item.label"></div>
              </template>
              <template #default>
                <div style="padding-left:0px;" v-html="item.value"></div>
              </template>
            </van-cell>
            <!--<van-cell :title="item.title" :value="item.value" :label="item.label" @click="openCard(item[idobject + '_id'])"/>-->
            <template slot="right">
              <van-button v-if="!item[idobject + '_billstatus'] || item[idobject + '_billstatus'] === '40282e81535903f901535938d3be0748' || item[idobject + 'billstatus'] === '2c9a2d9270d1ac600170d33c44b800a7'" class="swipe-button" square type="danger" text="删除" @click="del(item[idobject + '_id'])" />
              <van-button v-else class="swipe-button" square disabled type="danger" text="删除" @click="del(item[idobject + '_id'])" />
            </template>
          </van-swipe-cell>
        </template>
      </van-list>
    </van-pull-refresh>
    <van-tabbar v-model="active" safe-area-inset-bottom v-if="idobject !== 'currentstock'">

      <template v-if="idobject === 'sorder' || idobject === 'arvouch' || (sdlist && sdlist.length > 0)">
        <van-tabbar-item @click="showPopup">新增</van-tabbar-item>
      </template>
      <template v-else-if="idobject === 'activity'">
        <van-tabbar-item @click="openActivityNew">新增</van-tabbar-item>
      </template>
      <template v-else-if="idobject === 'qiandao'">
        <van-tabbar-item @click="openQiandaoNew">新增</van-tabbar-item>
      </template>
      <template v-else-if="idobject === 'fpinfor1'">
        <!-- <van-tabbar-item @click="billScan">发票扫码</van-tabbar-item> -->
        <van-tabbar-item @click="uploadScanImg">上传发票图片</van-tabbar-item>
        <van-tabbar-item @click="openNew">新增</van-tabbar-item>
      </template>
      <!-- 默认都可以新增-->
      <template v-else>
        <van-tabbar-item @click="openNew">新增</van-tabbar-item>
      </template>
    </van-tabbar>
    <van-popup v-model="sdshow" position="bottom" safe-area-inset-bottom>
      <template v-if="sdlist.length > 0">
        <van-cell v-for="sd in sdlist" :key="sd.index" @click="openSDList(sd.sdtype, sd.sdidview, sd.sdrelopeid, sd.sdsubviewid, sd.refob, sd.refobs)" :value="sd.sdtitle"></van-cell>
        <template v-if="batop_new"><van-cell clickable @click="openNew">新增</van-cell></template>
      </template>
    </van-popup>
  </div>
</template>

<script>
import Vue from 'vue'
import { Search, List, Cell, PullRefresh, Toast, Tabbar, TabbarItem, Popup, Icon, SwipeCell, Dialog, RadioGroup, Radio, CellGroup, Grid, GridItem, DropdownMenu, DropdownItem, TreeSelect, DatetimePicker, Picker } from 'vant'
import qs from 'qs'
import * as dd from 'dingtalk-jsapi'
import wx from 'weixin-js-sdk'
Vue.use(Search).use(List).use(Cell).use(PullRefresh).use(Toast).use(Tabbar).use(TabbarItem).use(Popup).use(Icon).use(SwipeCell).use(Dialog).use(Radio).use(RadioGroup).use(CellGroup).use(Grid).use(GridItem).use(DropdownMenu).use(DropdownItem).use(TreeSelect).use(DatetimePicker).use(Picker)
export default {
  name: 'list',
  data () {
    return {
      searchPh: '',
      title: this.$route.query.stitle,
      idobject: this.$route.query.idobject,
      idtemplate: this.$route.query.idtemplate,
      extract: this.$route.query.extract,
      sval: '',
      list: [],
      loading: false,
      finished: false,
      isLoading: false,
      active: 0,
      startline: 1,
      pagecount: 20,
      sdshow: false,
      searchshow: false,
      conditiondata: [],
      isflow: '',
      orderby: '',
      radiovalue: 'desc',
      value1: '',
      option1: [],
      mainactive: 0,
      items: [],
      indexflag: 0,
      sdlist: [],
      minDate: new Date(2020, 0, 1),
      currentDate: new Date(),
      maxDate: this.genMaxDate(),
      showDatePicker: false,
      showOpenRef: false,
      // 区域列表
      depcolumns: [],
      conditionValHidden: '',
      searchtags: [],
      searchedtags: {},
      batop_new: false,
      showForm: false
    }
  },
  created: function () {
    let _this = this
    document.title = _this.$route.query.stitle
    if (dd.env.platform !== 'notInDingTalk') {
      dd.ready(function () {
        dd.biz.navigation.setTitle({
          title: _this.$route.query.stitle
        })
      })
    }
  },
  beforeRouteLeave (to, form, next) {
    let _this = this
    document.title = _this.$store.state.crmtitle
    if (dd.env.platform !== 'notInDingTalk') {
      dd.ready(function () {
        dd.biz.navigation.setTitle({
          title: _this.$store.state.crmtitle
        })
      })
    }
    next()
  },
  mounted () {
    // //console.log('mounted')
    // -32是因为左右padding
    //console.log('count per line', Math.floor((screen.width - 32) * 2 / 3 / 12))
  },
  watch: {
    '$route' () {
      //console.log('list isreload变更', this.$store.state.isreload, this.$route)
      if (this.$store.state.isreload && this.$route.name === 'list') {
        // this.onLoad()
        // this.$store.commit('clearreload')
        // this.loading = false
        this.$router.go(0)
      }
    }
  },
  methods: {
    chooseTag (tagid) {
      this.$set(this.searchedtags, tagid, !this.searchedtags[tagid])
      //console.log('tag click', this.searchedtags[tagid], this.searchedtags)
    },
    genMaxDate () {
      let date = new Date()
      date.setFullYear(date.getFullYear() + 50)
      return date
    },
    confirmDate (date) {
      //console.log('date: ' + date)
      let year = date.getFullYear()
      let month = date.getMonth() + 1
      let day = date.getDate()
      this.conditiondata[this.mainactive].viewcondition_value = year + '-' + month + '-' + day
      this.showDatePicker = false
    },
    setValueForDatetime (val) {
      this.conditiondata[this.mainactive].viewcondition_comparison = val
      this.showDatePicker = true
    },
    onConfirmRef (value, index) {
      //console.log(`当前值：${value}, 当前索引：${index}`)
      this.conditiondata[this.mainactive].viewcondition_value = value
      this.showOpenRef = false
    },
    setValueForRef (val) {
      this.conditiondata[this.mainactive].viewcondition_comparison = val
      //console.log('datamodel1:' + JSON.stringify(this.conditiondata[this.mainactive]))

      this.$router.push({
        name: 'idownerMultiForFilter',
        params: {
          valuehidden1: this.conditionValHidden,
          datamodel: this.conditiondata[this.mainactive],
          obj: this
        }
      })
      // this.conditiondata[this.mainactive].viewcondition_comparison = val
      // // 获取列表
      // // alert(this.items[this.mainactive]['text'])
      // this.showOpenRef = true
      // this.axios({
      //   method: 'post',
      //   url: '/api/' + 'dep' + '.list.do'
      // }).then(res => {
      //   //console.log('list res:' + JSON.stringify(res))
      //   let _arr = res.data.jsondata.fieldValue
      //   for (let i = 0; i < _arr.length; i++) {
      //     this.depcolumns.push(_arr[i].dep_sname)
      //   }
      // }).catch(res => {
      //   Toast('获取区域列表异常，请联系管理员！')
      //   //console.log(res)
      // })
      //
      // //console.log('depcolumns:' + this.depcolumns)
    },
    formatter (type, val) {
      if (type === 'year') {
        return `${val}年`
      } else if (type === 'month') {
        return `${val}月`
      }
      return val
    },
    onLoad () {
      let data = {
        'startline': this.startline,
        'pagecount': this.pagecount,
        'condition': this.sval,
        'orderby': this.orderby,
        'ascdesc': this.radiovalue,
        'viewoption': this.value1,
        'extract': this.extract,
        'tags': JSON.stringify(this.searchedtags)
      }
      for (let i = 0; i < this.conditiondata.length; i++) {
        data[i + '_viewcondition_field'] = this.conditiondata[i].viewcondition_field
        data[i + '_viewcondition_relfield'] = this.conditiondata[i].viewcondition_relfield
        data[i + '_viewcondition_value'] = this.conditiondata[i].viewcondition_value
        data[i + '_viewcondition_comparison'] = this.conditiondata[i].viewcondition_comparison
        data[i + '_viewcondition_object'] = this.conditiondata[i].viewcondition_object
        data[i + '_viewcondition_uitype'] = this.conditiondata[i].viewcondition_uitype
      }
      /*
        averageCharWidth=fontSize×0.5（大约值，实际值可能需要调整）
        charsPerLine=averageCharWidth/divWidth
      */
      data['countperline'] = Math.floor((screen.width - 32) * 2 / 3 / 12)
      //console.log('data:', data)
      /* let templatelength = this.conditiondata.length + 1
      if (this.idtemplate != null && this.idtemplate !== '' && this.idtemplate !== undefined) {
        data[templatelength + '_viewcondition_field'] = 'idtemplate'
        data[templatelength + '_viewcondition_relfield'] = ''
        data[templatelength + '_viewcondition_value'] = this.idtemplate
        data[templatelength + '_viewcondition_comparison'] = 'eqref'
        data[templatelength + '_viewcondition_object'] = ''
      } */

      this.axios({
        method: 'post',
        url: '/api/' + this.idobject + '.list.do',
        data: qs.stringify(data)
      }).then(res => {
        //console.log('list res:', res)
        if (res.data.sdlist) {
          this.sdlist = res.data.sdlist
        }
        if (res.data.batop_new) {
          this.batop_new = res.data.batop_new
          //console.log('this.batop_new == true?', this.batop_new == true)
          //console.log('this.batop_new == false?', this.batop_new == false)
        }
        if (res.data.flag === '1') {
          Toast(res.data.des)
          if (res.data.des && res.data.des.indexOf('登录过期') >= 0) {
            this.loginout()
          }
        } else {
          this.isflow = res.data.jsondata.isflow
          let rsdata = res.data.jsondata.fieldValue
          let viewOptions = res.data.viewOptions
          this.value1 = res.data.viewoption
           if (res.data.viewcondition?.length > 0) {
            this.searchPh = res.data.viewcondition.map(i => i.viewcondition_title).join('/')
          }
          //console.log(viewOptions)
          this.option1 = []
          for (let i = 0; i < viewOptions.length; i++) {
            this.option1.push({ text: viewOptions[i][1], value: viewOptions[i][0] })
          }
          this.indexflag = this.list.length
          for (let i = 0; i < rsdata.length; i++) {
            this.list.push(rsdata[i])
          }
          if (this.idobject === 'activity') {
            //console.log(this.list)
            for (let i = 0; i < this.list.length; i++) {
              if (this.indexflag !== 0 && i < this.indexflag) {
                continue
              }
              // const dbegin = this.list[i].activity_dbegin
              // const dend = this.list[i].activity_dend
              // const jssj = this.list[i].activity_jssj
              // const bfxj = this.list[i].activity_bfxj
              // const picture = this.list[i].activity_picture
              // const state = this.list[i].activity_state

              // //console.log('i:' + i + '   dbegin:' + dbegin + '  dend: ' + dend + '  jssj:' + jssj + ' bfxj:' + bfxj + '  picture:' + picture)

              // if (state === '待拜访') {
              //   this.list[i].label = this.list[i].label + '<br><span style="color:#FF7F00">待拜访<span>'
              // }
              // else if (state === '待拜访') {
              //   this.list[i].label = this.list[i].label + '<br><span style="color:#0000FF">拜访中<span>'
              // }
              // else if (dend && (dend !== '1900-01-01 00:00:00.0')) {
              //   if (!bfxj || !picture) {
              //     this.list[i].label = this.list[i].label + '<br><span style="color:#FC8452">签到完成<span>'
              //   } else {
              //     this.list[i].label = this.list[i].label + '<br><span style="color:#00CD00">已完成<span>'
              //   }
              // }
              // else if ((!dbegin || dbegin === '1900-01-01 00:00:00.0')  && jssj && this.currenttime() >= jssj) {
              //   this.list[i].label = this.list[i].label + '<br><span style="color:#FF0000">已超期<span>'
              // }
            }
          }
          if (rsdata == null || rsdata.length === 0 || rsdata.length < this.pagecount) {
            this.loading = false
            this.finished = true
          } else {
            this.startline = this.startline + rsdata.length
            this.loading = false
          }
        }
        this.$store.commit('clearreload')
      }).catch(res => {
        this.reserror(res)
      })
    },
    onRefresh () {
      this.list = []
      this.startline = 1
      this.finished = false
      this.loading = true
      this.isLoading = false
      this.onLoad()
    },
    currenttime () {
      let d = new Date()
      let year = d.getFullYear()
      let month = this.change(d.getMonth() + 1)
      let day = this.change(d.getDate())
      let hour = this.change(d.getHours())
      let minute = this.change(d.getMinutes())
      let second = this.change(d.getSeconds())
      let time = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second
      return time
    },
    change (t) {
      if (t < 10) {
        return '0' + t
      } else {
        return t
      }
    },
    onSearch () {
      this.list = []
      this.startline = 1
      this.finished = false
      this.loading = true
      this.onLoad()
      this.showForm = false
    },
    onCancel () {
      this.sval = ''
    },
    chooseOrder (value) {
      this.orderby = value
    },
    showPopup () {
      this.sdshow = true
    },
    returnHome () {
      this.$router.push({ name: 'main' })
    },
    showFormPopup () {
      //console.log('form ...')
      this.showForm = true
    },
    showSearchPopup () {
      //console.log('conditiondata:' + this.conditiondata)
      if (this.conditiondata.length === 0) {
        let data = {}
        this.axios({
          method: 'post',
          url: '/api/' + this.idobject + '.query.do',
          data: qs.stringify(data)
        }).then(res => {
          if (res.data.flag === '1') {
            Toast(res.data.des)
            if (res.data.des && res.data.des.indexOf('登录过期') >= 0) {
              this.loginout()
            }
          } else {
            //console.log(res)
            this.searchtags = res.data.tags
            this.conditiondata = res.data.jsondata
            this.items = []
            if (this.conditiondata.length <= 0) {
              Toast('请先在开发平台配置高级查询条件')
              return
            }
            for (let i = 0; i < this.conditiondata.length; i++) {
              //console.log(this.conditiondata[i].viewcondition_title)
              this.items.push({ text: this.conditiondata[i].viewcondition_title })
            }
            this.searchshow = true
          }
        }).catch(res => {
          this.reserror(res)
        })
      } else {
        this.searchshow = true
      }
    },
    query () {
      this.list = []
      this.startline = 1
      this.finished = false
      this.loading = true
      this.searchshow = false
      this.onLoad()
    },
    clearquery () {
      for (let i = 0; i < this.conditiondata.length; i++) {
        this.conditiondata[i].viewcondition_value = ''
      }
      // this.searchshow = false
      this.orderby = ''
    },
    openNew () {
      this.sdshow = false
      if (this.idobject == 'bflx') {
        this.$router.push({
          name: 'bflxnew',
          query: { stitle: this.title, idobject: this.idobject, idtemplate: this.idtemplate }
        })
      } else {
        this.$router.push({
          name: 'new',
          query: { stitle: this.title, idobject: this.idobject, idtemplate: this.idtemplate }
        })
      }
    },
    openAccount3 (relopeid) {
      this.sdshow = false
      this.$router.push({
        name: 'refaccount3',
        params: {
          bo: 'account3',
          tobo: '',
          field: '',
          fieldref: '',
          viewid: '',
          conditionVal: '',
          conditionValHidden: '',
          classname: '',
          relopeid: relopeid
        }
      })
    },
    openActivityNew () {
      this.sdshow = false
      this.$router.push({ name: 'activitynew', query: { stitle: this.title, idobject: this.idobject, idtemplate: this.idtemplate, src: 'list' } })
    },
    openQiandaoNew () {
      this.sdshow = false
      this.$router.push({ name: 'qiandaonew', query: { stitle: this.title, idobject: this.idobject, idtemplate: this.idtemplate } })
    },
    openCard (itemid) {
      if (this.idobject === 'dailyreports' || this.idobject === 'weekreports' || this.idobject === 'monthreport1') {
        // 1. 把对象的置为已读
        // 2.在已读对象的已读字段中加上当前用户的id (如果已经已读则不用)
        this.updateYidu(this.idobject, itemid)
      }
      this.$router.push({ name: 'bflxcard', query: { stitle: this.title, itemid: itemid, idobject: this.idobject, idtemplate: this.idtemplate } })
    },
    updateYidu (obj, objid) {
      let data = { object: obj, objectid: objid }
      this.axios({
        method: 'post',
        url: '/api/' + this.idobject + '.updateyidu.do',
        data: qs.stringify(data)
      }).then(res => {
        if (res.data.flag === '1') {
          Toast(res.data.des)
          if (res.data.des && res.data.des.indexOf('登录过期') >= 0) {
            this.loginout()
          }
        } else {
          //console.log('更新已读成功!')
        }
      }).catch(res => {
        this.reserror(res)
      })
    },
    edit (itemid) {
      //console.log(this.idobject + '111')
      if (this.idobject === 'activity') {
        this.$router.push({ name: 'activityedit', query: { stitle: this.title, itemid: itemid, idobject: this.idobject, idtemplate: this.idtemplate } })
      } else {
        this.$router.push({ name: 'edit', query: { stitle: this.title, itemid: itemid, idobject: this.idobject, idtemplate: this.idtemplate } })
      }
    },
    submit (itemid) {
      let data = { [this.idobject + '_id']: itemid }
      this.axios({
        method: 'post',
        url: '/api/' + this.idobject + '.flowsubmit.do',
        data: qs.stringify(data)
      }).then(res => {
        if (res.data.flag === '1') {
          Toast(res.data.des)
          if (res.data.des && res.data.des.indexOf('登录过期') >= 0) {
            this.loginout()
          }
        } else {
          Toast(res.data.des + ' ')
          // 刷新列表
          this.onRefresh()
        }
      }).catch(res => {
        this.reserror(res)
      })
    },
    del (itemid) {
      Dialog.confirm({
        title: '删除',
        message: '确认删除吗？'
      }).then(() => {
        // on confirm
        let data = { [this.idobject + '_id']: itemid }
        this.axios({
          method: 'post',
          url: '/api/' + this.idobject + '.del.do',
          data: qs.stringify(data)
        }).then(res => {
          if (res.data.flag === '1') {
            Toast(res.data.des)
            if (res.data.des && res.data.des.indexOf('登录过期') >= 0) {
              this.loginout()
            }
          } else {
            Toast('删除成功')
            // 此处应该带着条件刷新列表
            this.onRefresh()
          }
        }).catch(res => {
          this.reserror(res)
        })
      }).catch(() => {
        // on cancel
      })
    },
    openSDList (sdtype, viewid, relopeid, subviewid, refob, refobs) {
      // let refob = 'psxy'
      // let refobs = 'psxys'
      // if (sdtype === 'zstg') {
      //   refob = 'hzxydl'
      //   refobs = 'dlprice'
      // } else if (sdtype === 'dispatch') {
      //   refob = 'dispatch'
      //   refobs = 'dispatchs'
      // }
      if (!subviewid) {
        // Toast('该对象未设置手机端视图')
        this.sdshow = false
        this.$router.push({ name: 'sdlist', query: { idobject: this.idobject, sdtype: sdtype, viewid: viewid, subviewid: subviewid, relopeid: relopeid, refobject: refob, subrefobject: refobs } })
      } else {
        this.sdshow = false
        this.$router.push({ name: 'sdlist', query: { idobject: this.idobject, sdtype: sdtype, viewid: viewid, subviewid: subviewid, relopeid: relopeid, refobject: refob, subrefobject: refobs } })
      }
    },
    openSDListNew (viewid, relopeid, subviewid, refob, refobs) {
      this.sdshow = false
      let sdtype = ''
      this.$router.push({ name: 'sdlist', query: { idobject: this.idobject, sdtype: sdtype, viewid: viewid, subviewid: subviewid, relopeid: relopeid, refobject: refob, subrefobject: refobs } })
    },
    uploadScanImg () {
      this.$router.push({
        name: 'billupload'
      })
    },
    billScan () {
      let userAgent = window.navigator.userAgent.toLowerCase()
      if (userAgent.indexOf('micromessenger') !== -1) {
        // alert("in wechat");
        this.weChatScan()
      } else if (userAgent.indexOf('dingtalk') !== -1) {
        // alert("in dingding");
        this.ddScanQR()
      } else {
        alert('请在微信或钉钉端使用此功能')
      }
      // //console.log(userAgent)
    },
    weChatScan () {
      var u = navigator.userAgent
      let url = sessionStorage.getItem('wxurl')
      var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
      var isQiye = /(wxwork)/i.test(u)
      if (!isIOS || isQiye) {
        url = location.href.split('#')[0]
      }
      let that = this
      this.axios({
        method: 'post',
        url: '/api/wechatscan.do',
        data: qs.stringify({
          'url': encodeURIComponent(url)
        })
      }).then(res => {
        let a = res.data
        //console.log(a)
        wx.config({
          debug: false,
          appId: a.appId,
          timestamp: a.timestamp,
          nonceStr: a.nonceStr,
          signature: a.signature,
          jsApiList: ['scanQRCode']
        })
        wx.error(function (res) {
          //console.log('微信js-sdk配置失败')
          Toast('微信配置异常，请联系系统管理员' + res.errMsg)
        })
        wx.ready(function () {
          wx.scanQRCode({
            needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
            scanType: ['qrCode', 'barCode'], // 可以指定扫二维码还是一维码，默认二者都有
            success: function (res) {
              var result = res.resultStr // 当needResult 为 1 时，扫码返回的结果
              that.axios({
                method: 'post',
                url: '/api/fpinfor1.wxscansave.do',
                data: qs.stringify({
                  'wxscanresult': result
                })
              }).then(res => {
                if (res.data.flag === '1') {
                  Toast(res.data.des)
                  if (res.data.des && res.data.des.indexOf('登录过期') >= 0) {
                    this.loginout()
                  }
                } else {
                  Toast(res.data.des + ' ')
                  that.onRefresh()
                }
              }).catch(res => {
                Toast('系统异常')
                //console.log(res)
              })
            },
            fail: function (res) {
              Toast('失败' + res.errMsg)
            }
          })
        })
      }).catch(res => {
        this.reserror(res)
      })
    },
    ddScanQR () {
      let that = this
      dd.ready(function () {
        dd.biz.util.scan({
          type: 'all',
          onSuccess: function (data) {
            var result = data.text
            that.axios({
              method: 'post',
              url: '/api/fpinfor1.wxscansave.do',
              data: qs.stringify({
                'wxscanresult': result
              })
            }).then(res => {
              if (res.data.flag === '1') {
                Toast(res.data.des)
                if (res.data.des && res.data.des.indexOf('登录过期') >= 0) {
                  this.loginout()
                }
              } else {
                Toast(res.data.des + ' ')
                that.onRefresh()
              }
            }).catch(res => {
              Toast('系统异常')
              //console.log(res)
            })
          },
          onFail: function (err) {
            alert(JSON.stringify(err))
          }
        })
      })
    }
  },
  activated () {
    // sdshow 特殊处理，后退时没有关闭，原因不明。
    this.sdshow = false
  }
}
</script>

<style src="../../assets/css/tags.css"></style>
<style scoped lang="scss">
.swipe-button {
  height: 100%;
}

.van-search--show-action {

  position: fixed;
  top: 0vh;
  left: 10vw !important;
  width: 75vw !important;
  z-index: 1;

}

/* .van-tabbar .van-tabbar-item {*/
/*  font-size: 16px;*/
/*  background-color: #5790df !important; !* 设置淡蓝色背景 *!*/
/*  width: 80% !important; !* 占满整行 *!*/
/*  margin:0 auto;*/
/*  text-align: center; !* 居中对齐文字 *!*/
/*  !*padding: 10px 0; !* 增加内边距 *!*!*/
/*  color:white;*/
/*}*/

.van-tabbar {
  display: flex;
  justify-content: center;
  padding-bottom: 10px !important;
}

.van-tabbar .van-tabbar-item {
  color: white;
  background-color: #5790df !important;
  width: 80% !important;
  flex: 0 0 80% !important;
  font-size: 14px;
}

.van-cell .van-cell__title {
  flex: 2;
}

.van-cell .van-cell__value {
  flex: 1;
}
</style>
